import 'package:flutter/material.dart';
import 'package:hainan/ModuleB/main.dart';
import 'banner.dart';

class Tijiao extends StatefulWidget {
  final int index;

  const Tijiao({super.key, required this.index});

  @override
  State<Tijiao> createState() => _TijiaoState();
}

class _TijiaoState extends State<Tijiao> {
  int _selectedDateIndex = 0;
  int _selectedTimeIndex = -1;
  int _quantity = 1;
  DateTime? _selectedCustomDate;
  final List<String> dates = ['今天', '明天', '后天', '更多\n日期'];
  final List<String> dateDetails = ['5-07', '5-08', '5-09', ''];
  final List<String> titles = [
    "夏木尼,小王子的玫瑰.",
    "钱塘往事|致那些远...",
    "胡日尔镇的美术馆",
    "致那些远去的记忆"
  ];
  final List<Map<String, dynamic>> timeSlots = [
    {'time': '08:00-10:00', 'remaining': 1000},
    {'time': '10:00-12:00', 'remaining': 1000},
    {'time': '12:00-14:00', 'remaining': 1000},
    {'time': '14:00-16:00', 'remaining': 1000},
    {'time': '16:00-18:00', 'remaining': 1000},
    {'time': '18:00-20:00', 'remaining': 1000},
  ];

  void _showDatePickerDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => Dialog(
        insetPadding: EdgeInsets.all(20),  // 设置边距
        shape: RoundedRectangleBorder(  // 添加圆角
          borderRadius: BorderRadius.circular(12),
        ),
        child: ConstrainedBox(
          constraints: BoxConstraints(
            maxHeight: MediaQuery.of(context).size.height * 0.8,
          ),
          child: Padding(
            padding: EdgeInsets.all(16),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 顶部操作栏
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    IconButton(
                      icon: Icon(Icons.close),
                      onPressed: () => Navigator.pop(context),
                    ),
                    Text('选择日期', style: TextStyle(fontSize: 18)),
                    TextButton(
                      onPressed: () {
                        if (_selectedCustomDate != null) {
                          final today = DateTime.now();
                          final tomorrow = today.add(Duration(days: 1));
                          final dayAfterTomorrow = today.add(Duration(days: 2));

                          // 检查是否选择了今天/明天/后天
                          if (_selectedCustomDate!.day == today.day) {
                            _selectedDateIndex = 0;
                          } else if (_selectedCustomDate!.day == tomorrow.day) {
                            _selectedDateIndex = 1;
                          } else if (_selectedCustomDate!.day == dayAfterTomorrow.day) {
                            _selectedDateIndex = 2;
                          } else {
                            _selectedDateIndex = 3; // 更多日期
                          }

                          setState(() {});
                          Navigator.pop(context);
                        }
                      },
                      child: Text('确定', style: TextStyle(color: Colors.orange)),
                    ),
                  ],
                ),
                Divider(),

                // 日历部分
                Expanded(
                  child: SingleChildScrollView(
                    child: CalendarDatePicker(
                      initialDate: _selectedCustomDate ?? DateTime.now(),
                      firstDate: DateTime.now(),
                      lastDate: DateTime.now().add(Duration(days: 365)),
                      onDateChanged: (date) {
                        if (date.isBefore(DateTime.now())) {
                          // 使用更醒目的提示方式
                          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("不可选择今日之前的日期")));
                        } else {
                          setState(() {
                            _selectedCustomDate = date;
                            _selectedDateIndex = -1;
                          });
                        }
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }


  String _getDisplayDate(int index) {
    if (index == dates.length - 1) {
      if (_selectedCustomDate != null) {
        final selected = _selectedCustomDate!;
        final today = DateTime.now();
        final tomorrow = today.add(Duration(days: 1));
        final dayAfterTomorrow = today.add(Duration(days: 2));

        // 只要选择了自定义日期，就显示具体日期
        return "${selected.month}-${selected.day}";
      }
      return '更多\n日期';
    }
    return dateDetails[index];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          SingleChildScrollView(
            child: Padding(
              padding: EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      GestureDetector(
                        onTap: () {
                          Navigator.push(context,
                              MaterialPageRoute(builder: (context) => MyApp()));
                        },
                        child: Image.asset("assets/images/icon_back.png"),
                      ),
                      SizedBox(width: 550),
                      Center(
                        child: Text("提交订单",
                            style:
                                TextStyle(fontSize: 23, color: Colors.black)),
                      )
                    ],
                  ),
                  SizedBox(height: 10),
                  // 景区信息
                  Row(
                    children: [
                      Image.asset("assets/images/列表图 ${widget.index + 1}.png",
                          width: 100),
                      const SizedBox(width: 15),
                      SizedBox(
                        height: 130,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              titles[widget.index],
                              style: TextStyle(
                                  fontSize: 20, fontWeight: FontWeight.bold),
                            ),
                            Text("今日可预定|随时退",
                                style: TextStyle(color: Colors.orange)),
                            GestureDetector(
                              onTap: () {
                                showModalBottomSheet(
                                  context: context,
                                  isScrollControlled: true,
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.vertical(
                                        top: Radius.circular(16)),
                                  ),
                                  builder: (context) {
                                    return Padding(
                                      padding: const EdgeInsets.all(16.0),
                                      child: Column(
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          Row(
                                            children: [
                                              Expanded(
                                                child: Center(
                                                  child: Text(
                                                    '购买须知',
                                                    style: TextStyle(
                                                        fontSize: 18,
                                                        fontWeight:
                                                            FontWeight.bold),
                                                  ),
                                                ),
                                              ),
                                              IconButton(
                                                icon: Icon(Icons.close),
                                                onPressed: () =>
                                                    Navigator.pop(context),
                                              )
                                            ],
                                          ),
                                          const Divider(),
                                          Align(
                                            alignment: Alignment.centerLeft,
                                            child: Text(
                                              '费用说明\n票价均执行淡季价\n\n服务说明\n1. 听从船长及安全管理员的安排。\n2. 乘船时必须穿好救生衣。\n3. 上下船时要等船停稳后依次上下，注意脚下，避免意外。\n4. 禁止在船上打闹、站在船头或不当行为。',
                                              style: TextStyle(fontSize: 16),
                                            ),
                                          ),
                                          SizedBox(height: 15),
                                          SizedBox(
                                            width: double.infinity,
                                            child: ElevatedButton(
                                              onPressed: () =>
                                                  Navigator.pop(context),
                                              style: ElevatedButton.styleFrom(
                                                shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
                                                  backgroundColor: Colors.orange,),
                                              child: GestureDetector(onTap: (){
                                                setState(() {
                                                  Navigator.pop(context);
                                                });
                                              },child: Text('确定', style:TextStyle(fontSize: 25))),
                                            ),
                                          )
                                        ],
                                      ),
                                    );
                                  },
                                );
                              },
                              child: Text(
                                "购买需知",
                                style: TextStyle(
                                  fontSize: 16,
                                  color: Colors.grey,
                                ),
                              ),
                            ),
                          ],
                        ),
                      )
                    ],
                  ),
                  Divider(height: 30),
                  // 日期选择
                  Text('日期选择', style: TextStyle(fontSize: 16)),
                  SizedBox(height: 12),
                  SizedBox(
                    height: 100,
                    child: ListView.builder(
                      scrollDirection: Axis.horizontal,
                      itemCount: dates.length,
                      itemBuilder: (context, index) {
                        final isMoreDateButton = index == dates.length - 1;
                        final isSelected = _selectedDateIndex == index ||
                            (isMoreDateButton && _selectedCustomDate != null && _selectedDateIndex == 3);

                        // 获取显示的日期文本
                        String displayDate = dates[index];
                        String displayDetail = dateDetails[index];

                        // 只有当选择了后天之后的日期时，才替换"更多日期"显示
                        if (isMoreDateButton && _selectedCustomDate != null && _selectedDateIndex == 3) {
                          final today = DateTime.now();
                          final dayAfterTomorrow = today.add(Duration(days: 2));
                          if (_selectedCustomDate!.isAfter(dayAfterTomorrow)) {
                            displayDate = "${_selectedCustomDate!.month}-${_selectedCustomDate!.day}";
                            displayDetail = "";
                          }
                        }

                        return GestureDetector(
                          onTap: () {
                            if (isMoreDateButton) {
                              _showDatePickerDialog(context);
                            } else {
                              setState(() {
                                _selectedDateIndex = index;
                                _selectedCustomDate = null;
                              });
                            }
                          },
                          child: Container(
                            width: 300,
                            margin: EdgeInsets.only(right: 10),
                            padding: EdgeInsets.all(8),
                            decoration: BoxDecoration(
                              color: isSelected
                                  ? Colors.orange.withOpacity(0.2)
                                  : Colors.grey.withOpacity(0.1),
                              borderRadius: BorderRadius.circular(8),
                              border: Border.all(
                                color: isSelected ? Colors.orange : Colors.transparent,
                              ),
                            ),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Text(displayDate, style: TextStyle(fontSize: 16)),
                                if (!isMoreDateButton || (isMoreDateButton && displayDetail.isNotEmpty))
                                  Text(displayDetail, style: TextStyle(fontSize: 12, color: Colors.grey)),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                  if (_selectedCustomDate != null)
                    Padding(
                      padding: EdgeInsets.only(top: 8),
                      child: Text(
                        "已选择: ${_selectedCustomDate!.month}月${_selectedCustomDate!.day}日",
                        style: TextStyle(color: Colors.blue),
                      ),
                    ),
                  Divider(height: 30),

                  // 场次选择
                  Text('门票场次', style: TextStyle(fontSize: 16)),
                  SizedBox(height: 6),
                  GridView.builder(
                    shrinkWrap: true,
                    gridDelegate:
                        const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      childAspectRatio: 3,
                      crossAxisSpacing: 10,
                      mainAxisSpacing: 10,
                    ),
                    itemCount: timeSlots.length,
                    itemBuilder: (context, index) {
                      return GestureDetector(
                        onTap: () {
                          setState(() {
                            _selectedTimeIndex = index;
                          });
                        },
                        child: Container(
                          decoration: BoxDecoration(
                            color: _selectedTimeIndex == index
                                ? Colors.orange.withOpacity(0.2)
                                : Colors.grey.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(8),
                            border: Border.all(
                              color: _selectedTimeIndex == index
                                  ? Colors.orange
                                  : Colors.transparent,
                            ),
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text(timeSlots[index]['time']),
                              SizedBox(height: 4),
                              Text('余${timeSlots[index]['remaining']}',
                                  style: TextStyle(color: Colors.grey)),
                            ],
                          ),
                        ),
                      );
                    },
                  ),
                  Divider(height: 30),
                  Row(
                    children: [
                      Text('购买数量', style: TextStyle(fontSize: 16)),
                      Spacer(),
                      IconButton(
                        icon: Icon(Icons.remove),
                        onPressed: () {
                          if (_quantity > 1) {
                            setState(() {
                              _quantity--;
                            });
                          }
                        },
                      ),
                      Text('$_quantity', style: const TextStyle(fontSize: 18)),
                      IconButton(
                        icon: const Icon(Icons.add),
                        onPressed: () {
                          if (_quantity < 10) {
                            setState(() {
                              _quantity++;
                            });
                          } else {
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(content: Text("最多可订10张")),
                            );
                          }
                        },
                      ),
                    ],
                  ),
                  SizedBox(height: 35),
                  Row(
                    children: [
                      Text('共$_quantity张门票，合计：￥${20 * _quantity}元',
                          style: const TextStyle(fontSize: 16)),
                      Spacer(),
                      Center(
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            primary: Colors.orange,
                            minimumSize: Size(200, 50),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(25),
                            ),
                          ),
                          onPressed: () {
                            final selectedDate = _selectedCustomDate ??
                                DateTime.now()
                                    .add(Duration(days: _selectedDateIndex));
                            print(
                                "提交订单，日期: ${selectedDate.month}月${selectedDate.day}日");
                            print(
                                "场次: ${timeSlots[_selectedTimeIndex]['time']}");
                            print("数量: $_quantity");
                            // 这里添加实际的订单提交逻辑
                          },
                          child: Text('提交订单', style: TextStyle(fontSize: 18)),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 40),
                  // 提交按钮
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
